import React, { useState } from "react";

type ChangeEvent = React.ChangeEvent<HTMLTextAreaElement>;
const FormState = () => {
  const [answer, setAnswer] = useState("");
  const [error, setError] = useState(Error);
  const [status, setStatus] = useState("typing");
  if (status === "success") {
    return <h1>That's right !</h1>;
  }
  const handleSubmit = async (e :React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setStatus("submitting");
	try {
      await submitForm(answer);
      setStatus("success");
    } catch (err) {
      setStatus("typing");
		if (err instanceof Error) {
			setError(err); // 类型安全地设置 error
		} else {
			setError(new Error("An unknown error occurred"));
		}
    }
  }

  const handleTextareaChange = (e :ChangeEvent) => {
    setAnswer(e.target.value);
  };

  return (
	  <>
		  <h2>City  Quiz</h2>
		  <p>
			  In which city is there a billboard that turns air into drinkable water?
		  </p>
		  <form onSubmit={handleSubmit}>
			  <textarea
				  value={answer}
				  onChange={handleTextareaChange}
				  disabled={status === "submitting"}
			  />
			  <br/>
			  <button disabled={ answer.length === 0 || status === "submitting"}>
				  Submit
			  </button>
			  {error !== null && <p className="Error">{error.message}</p>}
		  </form>
	  </>
  );
}

const submitForm = (answer :string) :Promise<void> => {
	// Pretend it's hitting the network.
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			let shouldError = answer.toLowerCase() !== 'lima'
			if (shouldError) {
				reject(new Error('Good guess but a wrong answer. Try again!'));
			} else {
				resolve();
			}
		}, 1500);
	});
};

export default FormState;